package com.lazy.netty.ex.bench;

import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lazy.netty.ex.bench.client.BenchClient;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.collection.CharCollections;

public class BenchClientMain {
    private static final Logger logger = LoggerFactory.getLogger(BenchClientMain.class);
    private static int connCount = 6000;
    private static int poolSize = 100;
    
    
    public static void main(String[] args) {
        String host = "192.168.1.178";
        String localHost = "192.168.0.202";
        int port = 8023;
        if (args.length == 2) {
            host = args[0];
            port = Integer.valueOf(args[1]);
        }
        
        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
        BenchClient bc = new BenchClient(host, port);
        bc.init();
        //bc.setLocalHost(localHost);
        
        for (int i = 0; i < connCount; i++) {
            executor.submit(new Task(bc));
        }
        
        ScheduledExecutorService scheduledExecutor  = Executors.newScheduledThreadPool(8);
        scheduledExecutor.scheduleAtFixedRate(new SendTask(bc.getMapChannels().values()), 0, 10, TimeUnit.SECONDS);
    }
    
    static class Task implements Runnable {
        BenchClient bc;
        
        public Task(BenchClient bc){
            this.bc = bc;
        }

        @Override
        public void run(){
            bc.connect();
            //ChannelFuture future = bc.connect().awaitUninterruptibly();
            //System.out.println("future is done." + future.isDone());
        }
    }
    
    static class SendTask implements Runnable {
        Collection<Channel> chCollection;
        
        public SendTask(Collection<Channel> channels){
            this.chCollection = channels; 
        }

        @Override
        public void run(){
            logger.info("Current thread = {} and total threads = {}", Thread.currentThread(), Thread.activeCount());
            for (Channel ch : chCollection) {
                ch.writeAndFlush(
                        "100bytettttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
                        + "100bytettttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
                        + "\r\n");
            }
        }
        
    }

}
